package com.example.service.medical;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.enums.ResultCodeEnum;
import com.example.exception.CustomException;
import com.example.mapper.medical.CountOfficeMapper;
import com.example.mapper.medical.DepartmentMapper;
import com.example.mapper.medical.DoctorMapper;
import com.example.mapper.medical.OfficeMapper;

import com.example.model.dto.OfficeDto;
import com.example.model.entity.medical.Doctor;
import com.example.model.entity.medical.Hospital;
import com.example.model.entity.medical.Office;
import com.example.model.vo.OfficeVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 科室表业务处理
 **/
@Service
public class OfficeService {

    @Resource
    private OfficeMapper officeMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private CountOfficeMapper countOfficeMapper;

    /**
     * 新增
     */
    public void add(Office office) {
        Office dbOffice = officeMapper.selectByUsername(office.getOfficeName());
        if (ObjectUtil.isNotNull(dbOffice)) {
            throw new CustomException(ResultCodeEnum.OFFICE_EXIST_ERROR);
        }
        officeMapper.insert(office);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        officeMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            officeMapper.deleteById(id);
        }
    }

    public void updateById(Office office) {
        // 获取要更新的办公室名称
        String officeName = office.getOfficeName();
        // 检查是否有其他记录使用相同的办公室名称
        Office dbOffice = officeMapper.selectByUsername(officeName);
        // 如果找到了记录，但其 ID 与正在更新的记录 ID 不同，表示名称冲突
        if (dbOffice != null && !dbOffice.getId().equals(office.getId())) {
            throw new CustomException(ResultCodeEnum.OFFICE_EXIST_ERROR);
        }

        // 更新记录
        officeMapper.updateById(office);
    }

    /**
     * 根据ID查询
     */
    public Office selectById(Integer id) {
        return officeMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<OfficeVO> selectAll(Office office) {
        return officeMapper.selectAll(office);
    }

    /**
     * 分页查询
     */
    public PageInfo<OfficeVO> selectPage(Office office, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OfficeVO> list = officeMapper.selectAll(office);
        return PageInfo.of(list);
    }

    /**
     * 查询挂号量靠前的科室
     * @return
     */
    public List<OfficeVO> selectTopOffice() {
        List<OfficeVO> officeVOS = officeMapper.selectAll(new Office());
        officeVOS.stream().forEach(officeVO -> {
            Integer officeId = officeVO.getId();
            List<Doctor> doctorList = doctorMapper.selectByOfficeId(officeId);
            AtomicReference<Integer> officeCount = new AtomicReference<>(0);
            doctorList.stream().forEach(doctor -> officeCount.updateAndGet(v -> v + doctor.getCount()));
            officeVO.setCount(officeCount.get());
        });
        officeVOS.sort((o1, o2) -> o2.getCount() - o1.getCount());
        return officeVOS;
    }
   /**
     * 根据信息查询科室
     * @param officeDto 科室信息
     * @return
    */
    public PageInfo<OfficeVO> selectByInfoPage(OfficeDto officeDto) {
        String departmentId= officeDto.getDepartmentId();
        PageHelper.startPage(officeDto.getPageNum(),officeDto.getPageSize());
        List<OfficeVO> officeList = officeMapper.selectByInfo(departmentId);
        Map<Integer, Integer> officeCountMap = new HashMap<>();
        officeList.forEach(officeVO -> {
            String departmentName = departmentMapper.selectById(officeVO.getDepartmentID()).getDepartmentName();
            officeVO.setDepartmentName(departmentName);
            List<Doctor> doctorList = doctorMapper.selectByOfficeId(officeVO.getId());
            AtomicReference<Integer> officeCount = new AtomicReference<>(0);
            doctorList.stream().forEach(doctor -> {
                Integer count = doctor.getCount();
                officeCount.updateAndGet(v -> v + count);
            });
            if (officeCount.get() == null) {
                officeVO.setCount(0);
            } else {
                officeVO.setCount(officeCount.get());
            }
            officeCountMap.put(officeVO.getId(), officeCount.get());
        });
        officeList.sort(new Comparator<Office>() {
            @Override
            public int compare(Office o1, Office o2) {
                return officeCountMap.get(o2.getId()).intValue() - officeCountMap.get(o1.getId());
            }
        });
/*        if (!officeDto.getCountIsBoolean()) {
            return page;
        }*/
        return PageInfo.of(officeList);
    }
}
